import { 
  AxesHelper,
  HemisphereLight,
  Mesh,
  PerspectiveCamera, 
  Scene, 
  WebGLRenderer,
  Material,
  DoubleSide,
} from "three"
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import stats from '../utils/stats'
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader"

let scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
// 不能设置为0
camera.position.set(-3, 13, 39)

const renderer = new WebGLRenderer({ antialias: true })
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setClearColor(0xeeeeee)
renderer.setSize(window.innerWidth, window.innerHeight)

document.body.appendChild(renderer.domElement)

new OrbitControls(camera, renderer.domElement)

// 添加坐标系
const axes = new AxesHelper(10)
scene.add(axes)

const light = new HemisphereLight(0xffffff, 0xcccccc, 1)
scene.add(light)

let mtlLoader = new MTLLoader()
mtlLoader.setPath('/models/butterfly/')
mtlLoader.load(
  'butterfly.mtl',
  materials => {
    materials.preload()

    const loader = new OBJLoader()
    loader.setMaterials(materials)
    loader.load(
      '/models/butterfly/butterfly.obj',
      mesh => {
        // move wings to more horizontal position
        [0, 2, 4, 6].forEach(i => {
          mesh.children[i].rotation.z = 0.3 * Math.PI
        });

        [1, 3, 5, 6].forEach(i => {
          mesh.children[i].rotation.z = -0.3 * Math.PI
        })

        // configure the wings,
        let wing1 = (mesh.children[5] as Mesh);
        (wing1.material as Material).side = DoubleSide;
        (wing1.material as Material).opacity = 0.9;
        (wing1.material as Material).depthTest = false;
        (wing1.material as Material).transparent = true;

        let wing2 = (mesh.children[5] as Mesh);
        (wing2.material as Material).side = DoubleSide;
        (wing2.material as Material).opacity = 0.9;
        (wing2.material as Material).depthTest = false;
        (wing2.material as Material).transparent = true;

        mesh.scale.set(80, 80, 80)

        mesh.rotation.x = 0.2
        // mesh.rotation.y = -1.3
    
        scene.add(mesh)
      }
    )
  }
)



function render(): void {
  stats.update()

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}

requestAnimationFrame(render)